const express = require("express");
const router = express.Router();
const moment = require('moment');
const PatientModel = require('../db/PatientModel');//患者模型
const CasetemplateModel = require('../db/CasetemplateModel');//病例模型
const SurgicalTreatmentModel = require("../db/SurgicalTreatmentModel");//外科治疗模型
const now = () => {
    return moment().format('YYYY-MM-DD HH:mm:ss')
}

//医生门诊查询分诊疗信息,分页查询
router.post('/list', function (req, res) {
    let searchtext = req.body.searchtext;
    let starttime = req.body.starttime;
    let endtime = req.body.endtime;
    let doctor_id = req.body.doctor_id;
    let status = req.body.status;
    let pageindex = req.body.pageindex || 1;//页码
    let pagesize = req.body.pagesize || 12;//每页显示数据条数  createtime: { $gte: starttime }, createtime: { $lte: endtime } 
    let query;
    let or = [];
    if (!doctor_id || !status) {
        return res.json({
            code: 201,
            mes: '缺少必要参数.'
        });
    }
    if (starttime || endtime) {
        query.createtime = { $gte: starttime + " 00:00:00", $lte: endtime + " 24:00:00" }
    };
    if (searchtext) {
        let reg = /^[0-9]+.?[0-9]*$/;
        const regs = new RegExp(searchtext)
        if (reg.test(searchtext)) {
            or.push({ userphone: { $regex: regs } })
        } else {
            or.push({ username: { $regex: regs } })
        }
        query.$or = or
    } else {
        if (status == 1) {
            query = { "registrationmes.registerpeople.id": doctor_id, "status": status, createtime: { $gte: moment().format('YYYY-MM-DD') + " 00:00:00", $lte: moment().format('YYYY-MM-DD') + " 24:00:00" } };
        }
        query = { "registrationmes.registerpeople.id": doctor_id, "status": status };
    }
    PatientModel.count(query).then(counts => {
        return PatientModel.find(query).skip(parseInt((pageindex - 1) * pagesize)).limit(parseInt(pagesize)).then(patient => {
            return res.json({
                code: 200,
                mes: '查询成功.',
                counts,
                data: patient
            });
        })
    }).catch(err => {
        return res.json({
            code: 201,
            mes: '查询失败.',
            data: err
        });
    })
});

//保存医生接诊信息
router.post('/acceptsSave', function (req, res) {
    const _id = req.body.id;
    const temp = req.body;
    if (temp.familydata) {
        temp.familydata = JSON.parse(req.body.familydata)
    }
    if (temp.registrationmes) {
        temp.registrationmes = JSON.parse(req.body.registrationmes)
    }
    if (temp.signmes) {
        temp.signmes = JSON.parse(req.body.signmes)
    }
    if (temp.seedoctormes) {
        temp.seedoctormes = JSON.parse(req.body.seedoctormes)
    }
    if (!_id) {
        return res.json({
            code: 201,
            mes: "缺少参数!"
        })
    }
    PatientModel.findById(_id).then(user => {
        if (user) {
            return PatientModel.update({ _id }, { $set: temp }).then(docs => {
                return res.json({
                    code: 200,
                    mes: '修改成功.'
                });
            }).catch(err => {
                return res.json({
                    code: 201,
                    mes: '修改失败.'
                });
            })
        } else {
            return res.json({
                code: 202,
                mes: '此ID不存在.'
            });
        }
    }).catch(err => {
        return res.json({
            code: 203,
            mes: '数据库错误,请稍后重试.'
        });
    })
});

//保存病历模板
router.use("/savetemplate", (req, res) => {
    let { id, name, department, doctor, createman, action, nowmedical, historymedical,
        personage, family, physique, laboratoryassist, treatmentoptions } = req.body;
    if (!doctor || !name || !department) {
        return res.json({
            code: 201,
            mes: "缺少必要参数!"
        })
    }
    let parse = {
        name, department, doctor, createman,
        createtime: now(), state: 1, action, nowmedical,
        historymedical, personage, family, physique, laboratoryassist, treatmentoptions
    }
    return CasetemplateModel.count().then(counts => {
        parse.id = counts + 1;
        return CasetemplateModel.create(parse).then(data => {
            return res.json({
                code: 200,
                mes: "保存成功!",
                data
            })
        })
    }).catch(err => {
        return res.json({
            code: 201,
            mes: "发生意外错误!",
            err
        })
    })
});
//完成就诊
router.use("/complete", (req, res) => {
    const _id = req.body.id;
    if (!_id) {
        return res.json({
            code: 201,
            mes: "缺少参数!"
        })
    }
    PatientModel.findById(_id).then(user => {
        if (user) {
            return PatientModel.update({ _id }, { $set: { status: 4 } }).then(docs => {
                return res.json({
                    code: 200,
                    mes: '修改成功.'
                });
            }).catch(err => {
                return res.json({
                    code: 201,
                    mes: '修改失败.'
                });
            })
        } else {
            return res.json({
                code: 202,
                mes: '此ID不存在.'
            });
        }
    }).catch(err => {
        return res.json({
            code: 203,
            mes: '数据库错误,请稍后重试.'
        });
    })
});
//费用预览
router.post("/previewFee", (req, res) => {
    let _id = req.body.id
    if (!_id) {
        return res.json({
            code: 201,
            mes: '缺少参数.'
        });
    }
    PatientModel.find({ _id }, { Feedetails: 1 }).then(data => {
        return res.json({
            code: 200,
            data,
            mes: '查询成功.'
        });
    }).catch(err => {
        return res.json({
            code: 203,
            err,
            mes: '查询成功错误,请稍后重试.'
        });
    })
})


module.exports = router;